// upload.js
const multer = require("multer");
const path = require("path");
const crypto = require("crypto");

// 设置存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "_temp/uploads/"); // 设置上传文件的存储目录
  },
  filename: function (req, file, cb) {
    // 设置文件名
    var name = Buffer.from(file.originalname, "latin1").toString("utf8");
    // 后缀名
    var extname = path.extname(name);
    var md5 = crypto.createHash("md5");
    var cryptostr = md5.update(`${Math.floor(Date.now())}`).digest("hex");
    cb(null, cryptostr + extname);
    // cb(null, Date.now() + "-" + file.originalname); // 设置上传文件的文件名
  },
});

// 文件过滤选项
const fileFilter = (req, file, cb) => {
  // 只接受图片文件
  if (file.mimetype.startsWith("image/")) {
    cb(null, true);
  } else {
    cb(new Error("只允许上传图片文件"), false);
  }
};

// 创建上传文件的中间件
const upload = multer({ storage: storage, fileFilter: fileFilter });

module.exports = upload;
